package com.gitee.wsl.compose.struct.game

import androidx.compose.runtime.Composable
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import com.gitee.wsl.ext.K
import com.gitee.wsl.ext.gameLoop

interface GameLoop {
    fun update(timeNanos: Long, deltaNs: Long, delta: Double)

    fun updatePhysics(timeNanos: Long, deltaNs: Long, delta: Double)
}


@Composable
fun GameLoop(loop: GameLoop) {
    // Create dedicated threads for each loop
    val physicsThread = remember { Dispatchers.Default.limitedParallelism(1) }
    val gameThread = remember { Dispatchers.Default.limitedParallelism(1) }

    // Physics Thread
    LaunchedEffect(Unit) {
        withContext(physicsThread) {
            K.gameLoop { timeNanos, deltaNs, delta ->
                //Performance.profilePhysics(deltaNs)
                loop.updatePhysics(timeNanos, deltaNs, delta)
            }
        }
    }

    // Game Thread
    LaunchedEffect(Unit) {
        withContext(gameThread) {
            K.gameLoop { timeNanos, deltaNs, delta ->
                //Performance.profileUpdates(deltaNs)
                loop.update(timeNanos, deltaNs, delta)
            }
        }
    }
}